package person.learn.listener;

import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.SmartApplicationListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import person.learn.event.ContentEvent;

/**
 * Created by barton on 16-1-26.
 * 1. ApplicationEvent 事件监听器，当applicationContext有事件推送时，此Listener的onApplicationEvent方法就会自动执行
 * 2. 订阅-发布模式/观察者模式
 * 3. 这是一个有序的监听器，其顺序取决于重写的getOrder()方法
 * 4. 在使用@Async时需要在SpringBootLearnApplication加异步调用的支持注解@EnableAsync
 */
@Component
public class Order1ContentListener implements SmartApplicationListener {
    //@Async
    @Override
    public void onApplicationEvent(final ApplicationEvent event) {
        // 不需要 instanceof。supportsEventType 已经指定其类型为ContentEvent.class

        // 结合@Async注解进行测试异步调用
        // 可能会造成getOrder()方法失效
       /*try {
            Thread.sleep(2000);
            System.out.println("Order1发送：" + event.getSource());
        } catch (Exception e) {
        }*/

        System.out.println("Order1发送：" + event.getSource());

    }

    @Override
    public boolean supportsEventType(Class<? extends ApplicationEvent> eventType) {
        return eventType == ContentEvent.class;
    }

    @Override
    public boolean supportsSourceType(Class<?> sourceType) {
        return sourceType == String.class;
    }

    @Override
    public int getOrder() {
        return 1;
    }
}
